package com.jacoco.incremental.source;

import com.jacoco.incremental.config.JacocoConfig;
import com.jacoco.incremental.utils.ViewInfo;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.io.*;

/**
 * 创建增量 js脚本
 */
public class ScriptResource {
    private final String CLASS_PATH = "${class_path}";
    private final String CLASS_DIFF = "${class_diff}";
    private final String SCRIPT_NAME = "incremental.js";

    private JacocoConfig jacoco;

    public void copybuild(JacocoConfig jacoco) {
        this.jacoco = jacoco;
        if (jacoco == null) {
            ViewInfo.error("JacocoConfig 不能为null");
            return;
        }
        copyResource();
    }

    /**
     * 根据git 名称 去寻找路径
     */
    private void copyResource() {
        BufferedReader reader = null;
        InputStream in = null;
        BufferedWriter bufferedWriter = null;
        try {
            StringBuilder builder = new StringBuilder();
            in = ScriptResource.class.getResourceAsStream(SCRIPT_NAME);
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = reader.readLine()) != null) {
                if (line.indexOf(CLASS_PATH) > -1) {
                    ViewInfo.info("增量文件：\n" + JSONArray.fromObject(jacoco.getClassPath()).toString());
                    builder.append("let allClazzPaths=" + JSONArray.fromObject(jacoco.getClassPath()).toString() + ";");
                } else if (line.indexOf(CLASS_DIFF) > -1) {
                    ViewInfo.info("差异信息:\n" + JSONObject.fromObject(jacoco.getDiffInfos()).toString());
                    builder.append("let allClazzDiffs=" + JSONObject.fromObject(jacoco.getDiffInfos()).toString() + ";");
                } else {
                    builder.append(line);
                }
            }
            bufferedWriter = new BufferedWriter(new FileWriter(this.createFile()));
            bufferedWriter.write(builder.toString());
            bufferedWriter.flush();
        } catch (IOException e) {
            ViewInfo.error(e.getMessage());
        } finally {
            try {
                if (in != null) in.close();
                if (reader != null) reader.close();
                if (bufferedWriter != null) bufferedWriter.close();
            } catch (IOException e) {
                ViewInfo.error(e.getMessage());
            }
        }
    }

    /**
     * file path =
     *
     * @return
     */
    private File createFile() {
        File file = new File(this.jacoco.getJacocoPathReport() + "/jacoco-resources/" + SCRIPT_NAME);
        try {
            if (file.exists()) file.delete();
            if (!file.createNewFile()) {
                ViewInfo.error(file.getAbsolutePath() + " 文件创建失败！");
            }
        } catch (IOException e) {
            ViewInfo.error(e.getMessage());
        }
        return file;
    }
}
